<template>
  <div class="common-wrap">
    <div class="cabinet">
      <LeftRightStretching>
        <template #left>
          <QueryForm
            ref="conditionForm"
            module="cabinet"
            :searchBtnLoading="loading"
            v-model:searchForm="searchForm"
            v-model:search-column="searchColumn"
            @handle-search="onSearch"
          />
          <div style="padding: 0 10px">
            <MyTable
              id="MyTableCabinet"
              tableId="cabinet"
              :columns="columns"
              :dataSource="dataSource"
              keyField="id"
              :columnMinWidth="100"
              :loading="loading"
              ref="commonTable"
              moduleName="cabinet"
              @handleSelectionChange="handleSelectionChange"
            ></MyTable>
          </div>
        </template>
        <template #right>
          <div v-loading="rightLoading">
            <div
              :class="[
                'right-card',
                { 'right-card-box-shadow': selectedIndex === index },
              ]"
              v-for="(item, index) in rightData"
              :key="item.id"
              @click="selectedIndex = index"
            >
              <div class="flex-wrap right-wrap" :data-index="index">
                <div class="card-nav flex-center">
                  <el-icon
                    style="cursor: pointer; margin-bottom: 9px"
                    size="25"
                    v-if="!item.isType"
                    @click.stop="item.isType = !item.isType"
                    ><CaretTop
                  /></el-icon>
                  <el-icon
                    style="cursor: pointer; margin-bottom: 9px"
                    size="25"
                    v-else
                    @click.stop="item.isType = !item.isType"
                    ><CaretBottom
                  /></el-icon>
                  <span
                    style="font-size: 16px; font-weight: bold"
                    class="margin-left"
                    >{{ item.soNo }}</span
                  >
                  <el-tag effect="light" type="info" class="margin-left">
                    {{ $t("柜号:") }}{{ item.containerNo }}
                  </el-tag>
                </div>
                <el-tag effect="light" type="info" class="margin-left">
                  {{ item.specificationsName || "-" }}
                </el-tag>
                <el-tag
                  effect="light"
                  :type="item.goodsTypeName != 'DG' ? 'info' : 'danger'"
                  class="margin-left"
                >
                  {{ item.goodsTypeName || "-" }}
                </el-tag>
                <el-tag effect="light" type="primary" class="margin-left">
                  {{ $t(item.lineName || "-") }}
                </el-tag>
                <div class="flex-center margin-left">
                  <span>{{ $t(item.loadingPortName || "-") }}</span>
                  <el-icon style="color: #a79f9f; font-size: 16px"
                    ><CaretRight
                  /></el-icon>
                  <span
                    >{{ $t(item.dischargePortName || "-") }},{{
                      $t(item.deliveryPortName || "-")
                    }}</span
                  >
                </div>
                <div class="flex-center margin-left">
                  <span class="left-margin-color">{{ $t("船名/航次") }}</span>
                  <span>{{ $t(item.vesselName || "-") }}</span>
                  <span>/</span>
                  <span>{{ $t(item.voyageNo || "-") }}</span>
                </div>
                <div class="flex-center margin-left">
                  <span class="left-margin-color">
                    {{ $t("船公司") }}
                  </span>
                  <span>
                    {{ $t(item.providerName || "-") }}
                  </span>
                </div>
                <div class="flex-center margin-left">
                  <span class="left-margin-color">
                    {{ $t("ETD") }}
                  </span>
                  <span>
                    {{ item.estimatedTimeDeparture || "-" }}
                  </span>
                </div>
                <div class="flex-center margin-left">
                  <span class="left-margin-color">
                    {{ $t("体积(CBM)") }}
                  </span>
                  <span class="left-margin-color">
                    <span style="color: #3f3939">{{
                      item.totalVolume || "-"
                    }}</span>
                    /{{ item.maxCubicCapacity || "-" }}
                  </span>
                  <el-tag effect="light" type="primary">
                    {{
                      calculatePercentage(
                        item.totalVolume || 0,
                        item.maxCubicCapacity || 0
                      )
                    }}
                  </el-tag>
                </div>
                <div class="flex-center margin-left">
                  <span class="left-margin-color">
                    {{ $t("毛重(KG)") }}
                  </span>
                  <span class="left-margin-color">
                    <span style="color: #3f3939">
                      {{ item.totalGrossWeight || "-" }}</span
                    >
                    /{{ item.maxGrossWeight || "-" }}
                  </span>
                  <el-tag effect="light" type="primary">
                    {{
                      calculatePercentage(
                        item.totalGrossWeight || 0,
                        item.maxGrossWeight || 0
                      )
                    }}
                  </el-tag>
                </div>
                <div class="flex-center margin-left" v-show="item.isType">
                  <el-button
                    size="small"
                    @click="onAdd(item)"
                    :disabled="multipleSelection.length === 0"
                  >
                    {{ $t("添加") }}
                  </el-button>
                  <el-button
                    size="small"
                    @click="onRemove(item)"
                    :disabled="
                      !item.multipleSelection ||
                      item.multipleSelection?.length === 0
                    "
                  >
                    {{ $t("移除") }}
                  </el-button>
                </div>
                <div style="width: 100%" v-show="item.isType">
                  <MyTable
                    tableId="cabinet123456"
                    :columns="columns"
                    :dataSource="item.oceanOrderList"
                    keyField="id"
                    :columnMinWidth="100"
                    :loading="false"
                    :maxHeight="300"
                    @handleSelectionChange="
                      handleSelectionChangeCabinet($event, item)
                    "
                  ></MyTable>
                </div>
              </div>
            </div>
          </div>
        </template>
      </LeftRightStretching>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref, onBeforeUnmount } from "vue";
import * as api from "@/api/index.js";
import { useRoute } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import { calculatePercentage, numberSum, debounce } from "@/utils/mUtils.js";
import Sortable from "sortablejs";
import i18n from "@/lang/index.js";
const route = useRoute();
defineOptions({
  name: "Cabinet",
});
const loading = ref(false);
const searchForm = ref({});
const searchColumn = ref([
  {
    type: "label_input",
    label: "业务单号",
    prop: "typeCode",
    span: 12,
  },
]);
const dataSource = ref([]);
const columns = ref([
  {
    type: "checkbox",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    field: "trackingNo",
    title: "业务单号",
    width: 140,
    dragSort: true,
  },
  {
    field: "subProductName",
    title: "渠道",
  },
  {
    field: "destWarehouseName",
    title: "仓库",
    width: 100,
  },
  {
    field: "destWarehouseCountryName",
    title: "目的国",
    width: 90,
  },
  {
    field: "orderStatus",
    title: "节点状态",
    width: 100,
  },
  {
    field: "inStoragePcs",
    title: "件数",
    width: 80,
  },
  {
    field: "inStorageWeight",
    title: "重量",
    width: 80,
  },
  {
    field: "inStorageVolume",
    title: "体积",
    width: 80,
  },
  {
    field: "goodsTypeName",
    title: "货物类型",
  },
  {
    field: "includeTaxFlag",
    title: "是否退税",
    formatter: ({ cellValue }) => {
      const obj = {
        0: "不退税",
        1: "退税",
      };
      return obj[cellValue] || "-";
    },
  },
  {
    field: "containerRemark",
    title: "排柜备注",
  },
  {
    field: "remark",
    title: "备注",
  },
  {
    field: "customerNameZh",
    title: "客户",
  },
  {
    field: "createTime",
    title: "创建时间",
  },
]);
const rightData = ref([]);
const multipleSelection = ref([]);
const selectedIndex = ref(0);
const rightLoading = ref(false);
const rightIndex = ref();
const timeout = ref(null);
onMounted(() => {
  getByIds();
});

const getByIds = async () => {
  try {
    const ids = route.query.id.split(",");
    rightLoading.value = true;
    const { data } = await api.default.oceanFreight.cabinetArrangement.getByIds(
      {
        idList: ids,
        operationFlag: true,
      }
    );
    rightLoading.value = false;
    if (rightData.value.length) {
      rightData.value = rightData.value.map((item, index) => {
        return {
          ...data[index],
          isType: item.isType,
        };
      });
      onSearch();
      return;
    }
    rightData.value = data || [];
    rightData.value[selectedIndex.value].isType = true;
    searchForm.value.lineDetailCode = data[0].lineDetailCode;
    onSearch();
    nextTick(() => {
      const rightWrap = document.getElementsByClassName("right-wrap");
      onSortable(rightWrap);
    });
  } catch (error) {
    rightLoading.value = false;
  }
};
const onSortable = (arr) => {
  const MyTableCabinet = document.getElementById("MyTableCabinet");
  const body =
    MyTableCabinet.getElementsByClassName("vxe-table--body")[0].querySelector(
      "tbody"
    );
  MyTableCabinet.addEventListener("mousemove", function (event) {
    rightIndex.value = null;
  });
  Sortable.create(body, {
    group: {
      name: "shared",
      pull: (e) => {
        onDataRight(e.el.dataset.index);
      },
    },
    animation: 150,
    sort: false,
    disabled: false,
    draggable: ".vxe-body--row",
    onEnd: function (/**Event*/ evt) {
      timeout.value = setTimeout(() => {
        if (!rightIndex.value) return;
        rowInsertDragend(evt.oldIndex);
      }, 500);
    },
  });
  for (let i = 0; i < arr.length; i++) {
    Sortable.create(arr[i], {
      group: {
        name: "shared",
        pull: false, // 不允许拖拽进这个列表
        put: false,
      },
      animation: 150,
      draggable: "null",
      sort: false,
    });
  }
};
onBeforeUnmount(() => {
  const MyTableCabinet = document.getElementById("MyTableCabinet");
  MyTableCabinet.addEventListener("mousemove", function (event) {});
  clearTimeout(timeout.value);
});
const onSearch = () => {
  loading.value = true;
  api.default.order.maritimeAdministration
    .pendingList({
      ...searchForm.value,
    })
    .then((res) => {
      dataSource.value = res.data;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
const handleSelectionChange = (list) => {
  multipleSelection.value = list;
};
const handleSelectionChangeCabinet = (list, item) => {
  item.multipleSelection = list;
};
const onAdd = (item) => {
  const ids = multipleSelection.value.map((item) => item.id);
  const params = {
    id: item.id,
    orderIdList: ids,
  };
  onEdit(params);
};
const onRemove = (item) => {
  const ids = item.multipleSelection.map((item) => item.id);
  const params = {
    id: item.id,
    orderIdList: ids,
  };
  api.default.oceanFreight.cabinetArrangement
    .removeBoundOrder({
      ...params,
    })
    .then(() => {
      ElMessage.success("移除成功");
      getByIds();
    })
    .catch(() => {
      getByIds();
    });
};
const rowInsertDragend = (index) => {
  const data = dataSource.value[index];
  const { inStorageWeight, inStorageVolume, forecastVolume, forecastWeight } =
    data;
  const right = rightData.value[rightIndex.value];
  const { totalVolume, totalGrossWeight, maxCubicCapacity, maxGrossWeight } =
    right;
  const volume = numberSum([
    inStorageVolume || forecastVolume || 0,
    totalVolume || 0,
  ]);
  const weight = numberSum([
    inStorageWeight || forecastWeight || 0,
    totalGrossWeight || 0,
  ]);
  const params = {
    id: right.id,
    orderIdList: [data.id],
  };
  if (
    (maxCubicCapacity && volume > maxCubicCapacity) ||
    (maxGrossWeight && weight > maxGrossWeight)
  ) {
    ElMessageBox.confirm(
      i18n.global.t("当前数据体积或重量超出最大限制！"),
      i18n.global.t("提示"),
      {
        confirmButtonText: i18n.global.t("确定"),
        cancelButtonText: i18n.global.t("取消"),
        type: "warning",
      }
    )
      .then(() => {
        onEdit(params);
      })
      .catch(() => {});
    return;
  }
  onEdit(params);
};
const onEdit = (params) => {
  api.default.oceanFreight.cabinetArrangement
    .edit({
      ...params,
    })
    .then(() => {
      ElMessage.success("排柜成功");
      getByIds();
    })
    .catch(() => {
      getByIds();
    });
};
const onDataRight = (index) => {
  rightIndex.value = index;
};
</script>

<style lang="scss" scoped>
.cabinet {
  height: 100%;
  color: #3f3939;
}
.right-card {
  padding: 10px;
  margin: 10px;
  border: 1px solid #cccccc69;
  border-radius: 10px;
  cursor: pointer;
}
.right-card-box-shadow {
  box-shadow: 0px 0px 5px 0px #5e8eff69;
}
.card-nav {
}
.flex-center {
  display: flex;
  align-items: center;
}
.left-margin-color {
  color: #979595;
  margin-right: 5px;
}
.margin-left {
  margin-left: 10px;
  margin-bottom: 10px;
}
.flex-wrap {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>